/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package administratorGUI;

import java.util.List;
import javax.swing.*;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.YES_NO_OPTION;
import static javax.swing.JOptionPane.YES_OPTION;
import model.*;
import org.jdesktop.beansbinding.Binding;
import supermarket.EntityManagerFactory;

/**
 * Πίνακας Καταστημάτων
 */
public class StoreForm extends javax.swing.JInternalFrame {

    /**
     * Constructor
     */
    public StoreForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : EntityManagerFactory.getEntityManager();
        storeQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPUEntityManager.createQuery("SELECT s FROM Store s");
        storeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : storeQuery.getResultList();
        newStoreButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        storeTable = new javax.swing.JTable();
        editButton = new javax.swing.JButton();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Διαχείριση Καταστημάτων");

        newStoreButton.setText("Νέο κατάστημα");
        newStoreButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newStoreButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeList, storeTable, "STORE_BIND");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Διεύθυνση");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(storeTable);

        editButton.setText("Επεξεργασία");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(newStoreButton)
                    .add(editButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(deleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[] {deleteButton, editButton, newStoreButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(newStoreButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(editButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(deleteButton)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE)
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rebindStoreTable() {
        Binding b = bindingGroup.getBinding("STORE_BIND");
        b.unbind();
        b.bind();
    }


    /**
     * Button: Διαγραφή
     * @param evt 
     */
    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // Ελέγχω αν υπάρχει επιλεγμένο Row στο Table
        int row = storeTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                    "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }
        
        Store store = storeList.get(row);
        EntityManagerFactory.getEntityManager().refresh(store);
        
        // Warning αν στο Κατάστημα έχουμε ορίσει προϊόντα
        if (!store.getProductList().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Έχετε συσχετίσει το "
                    + "κατάστημα με " + store.getProductList().size()
                    + " προϊόντα.\nΑν επιλέξετε 'Διαγραφή', θα διαγράψετε "
                    + "και τους συσχετισμούς.", "Προσοχή", INFORMATION_MESSAGE);
        }
        
        // Warning αν από το Κατάστημα έχουν γίνει Αγορές
        if (!store.getPurchaseList().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Έχετε πραγματοποιήσει "
                    + store.getPurchaseList().size() + " Αγορές από το "
                    + "συγκεκριμένο κατάστημα.\nΑν επιλέξετε 'Διαγραφή', "
                    + "θα διαγράψετ και τις Αγορές.", "Προσοχή", INFORMATION_MESSAGE);
        }
        
        // Ερώτηση
        if (JOptionPane.showConfirmDialog(this,
                "Να διαγραφεί η επιλεγμένη εγγραφη;",
                "Διαγραφή", YES_NO_OPTION) == YES_OPTION) {

            SuperMarketPUEntityManager.getTransaction().begin();
            SuperMarketPUEntityManager.remove(store);
            SuperMarketPUEntityManager.getTransaction().commit();
            storeList.clear();
            storeList.addAll(storeQuery.getResultList());
            rebindStoreTable();
            storeTable.updateUI();
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    /**
     * Button: Νέο Κατάστημα
     *
     * @param evt
     */
    private void newStoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newStoreButtonActionPerformed
        // TODO add your handling code here:
        NewStoreDialog ns = new NewStoreDialog(null, true);
        ns.setLocationRelativeTo(this);

        ns.setVisible(true);
        if (ns.isValidForSave()) {
            saveRecord (ns);
        }
    }//GEN-LAST:event_newStoreButtonActionPerformed

    /**
     * Button: Επεξεργασία
     * @param evt 
     */
    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
        // TODO add your handling code here:
        int row = storeTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                    "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }

        Store currentStore = storeList.get(row);
        NewStoreDialog ns = new NewStoreDialog(null, true);
        ns.setLocationRelativeTo(this);
        ns.setStore(currentStore);
        ns.setVisible(true);

        if (ns.isValidForSave()) {
            saveRecord(ns, currentStore);
        }
    }//GEN-LAST:event_editButtonActionPerformed

    
    /**
     * Save Record (mode: Edit Record)
     */
    private void saveRecord (NewStoreDialog ns, Store store) {
        store.setName(ns.getStoreName());
        store.setAddress(ns.getStoreAddress());
        
        SuperMarketPUEntityManager.getTransaction().begin();
        SuperMarketPUEntityManager.persist(store);
        SuperMarketPUEntityManager.getTransaction().commit();
        storeList.clear();
        storeList.addAll(storeQuery.getResultList());
        rebindStoreTable();
        storeTable.updateUI();
    }
    
    /**
     * Save Record (mode: New Record)
     */
     private void saveRecord (NewStoreDialog ns) {
         saveRecord (ns, new Store());
     }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton newStoreButton;
    private java.util.List<model.Store> storeList;
    private javax.persistence.Query storeQuery;
    private javax.swing.JTable storeTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
